/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月5日 下午3:54:42
 */

package datang.dtdb.transaction.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import datang.dtdb.exceptions.TransactionException;
import datang.dtdb.session.TransactionIsolationLevel;
import datang.dtdb.transaction.Transaction;

/**
 * 调用connection的方法
 */
public class JdbcTransaction implements Transaction {

	/**
	 * 是否自动提交
	 */
	private boolean autoCommit;

	/**
	 * 连接
	 */
	private DataSource dataSource;

	/**
	 * 保存该连接用于提交或回滚事务
	 */
	private Connection connection;

	/**
	 * 用户指定隔离级别
	 */
	private TransactionIsolationLevel level;

	public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
		this.dataSource = dataSource;
		this.autoCommit = autoCommit;
		this.level = level;
	}

	/**
	 * 提交事务，connection不能为null,并且autoCommit=false
	 */
	@Override
	public void commit() {
		try {
			if (connection != null && !autoCommit) {
				connection.commit();
			}
		} catch (Exception e) {
			throw new TransactionException("提交事务异常", e);
		}
	}

	/**
	 * 回滚事务，connection不能为null,并且autoCommit=false
	 */
	@Override
	public void rollback() {
		try {
			if (connection != null && !autoCommit) {
				connection.rollback();
			}
		} catch (Exception e) {
			throw new TransactionException("回滚事务异常", e);
		}
	}

	/**
	 * 调用连接池的关闭连接方法。
	 * */
	@Override
	public void close() {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			throw new TransactionException("关闭连接异常", e);
		}
	}

	/**
	 * 从数据源获取连接,设置隔离级别，并保存连接用于commit或rollback
	 */
	@Override
	public Connection getConnection() {
		try {
			connection = dataSource.getConnection();
			connection.setTransactionIsolation(level.getLevel());
			connection.setAutoCommit(autoCommit);
			return connection;
		} catch (SQLException e) {
			throw new TransactionException("JdbcTransaction获取连接失败", e);
		}
	}
}
